package com.linewell.export.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linewell.export.dao.PbdBaseDeviceMapper;
import com.linewell.export.entity.PbdBaseDevice;
import com.linewell.export.service.IPbdBaseDeviceService;
import com.linewell.export.util.PubUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Title: PbdBaseDeviceServiceImpl
 * @description:
 * @author: pzhongqaing@linewell.com
 * @since: 2020年09月22日 10:52
 */
@Service
public class PbdBaseDeviceServiceImpl extends ServiceImpl<PbdBaseDeviceMapper, PbdBaseDevice> implements IPbdBaseDeviceService {

    Logger logger = LoggerFactory.getLogger(PbdBaseDeviceServiceImpl.class);

    private List<String> errorList = new ArrayList<>();

    private int totalNum = 0;

    @Autowired
    private PbdBaseDeviceMapper deviceMapper;

    /**
     * 根据code更新
     * @param list excel文件
     * @return 是否
     */
    @Override
    public boolean updateByCode(List<String> list) {
        if (null == list || list.size() < 1) {
            logger.error("excel获取为空，请检查后重试！");
            return false;
        }
        logger.info("Excel读取的列表：" + list);
        List<PbdBaseDevice> devices = deviceMapper.listByDevNoAndType(list, "8");
        if (devices == null || devices.size() < 1) {
            logger.info("更新失败，数据库未存在相关设备编号");
            return false;
        }
        totalNum = devices.size();
        errorList = new ArrayList<>();
        boolean flag = false;
        List<PbdBaseDevice> updateList = new ArrayList<>();
        for (PbdBaseDevice device : devices) {
            device = setDeviceInfo(device);
            if (device == null) {
                continue;
            }
            updateList.add(device);
        }
        if (updateList.size() > 0) {
            flag = this.updateBatch(updateList);
        }
        if (errorList.size() > 0) {
            logger.warn("未更新条数：" + errorList.size() + "，设备编号为【" + PubUtils.join(errorList) + "】");
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatch(List<PbdBaseDevice> list) {
        if (list == null || list.size() < 1) {
            return false;
        }
        try {
            int num = 0;
            for (PbdBaseDevice device : list) {
                boolean b = deviceMapper.updateByUnid(device);
                if (b) {
                    num ++;
                }else {
                    errorList.add(device.getDevNo());
                }
            }
            logger.info("完成更新条数：" + num + "/" + totalNum);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }
    }


    private PbdBaseDevice setDeviceInfo(PbdBaseDevice device) {
        if (device == null) {
            return null;
        }
        String faceId = device.getDevFaceId();
        String engine = device.getDevFaceEngine();
        // 判断faceId和engine是否为空
        if (PubUtils.isEmpty(engine) && PubUtils.isEmpty(faceId)) {
            device.setDevFaceId(device.getDevNo());
            device.setDevFaceEngine("ali");
            device.setDevFaceGbcode(device.getDevNo());
        } else {
            String[] faceIds = faceId.split(",");
            String[] engines = engine.split(",");
            // 判断分割后faceIds与engine长度是否匹配
            if (faceIds.length != engines.length) {
                errorList.add(device.getDevNo());
                logger.error("设备编号<" + device.getDevNo() + ">中：DEV_FACE_ID与DEV_FACE_ENGINE不匹配！" );
                return null;
            }
            // 分割后依旧为空 进行赋值
            if (PubUtils.isEmpty(faceIds) && PubUtils.isEmpty(engines)) {
                device.setDevFaceId(device.getDevNo());
                device.setDevFaceEngine("ali");
                device.setDevFaceGbcode(device.getDevNo());
            }else {
            // 不为空操作
                if (engine.contains("ali")) {
                    // 已有ali 引擎进行替换
                    int index = Arrays.asList(engines).indexOf("ali");
                    faceIds[index] = device.getDevNo();
                    String newFaceId = PubUtils.join(faceIds);
                    device.setDevFaceId(newFaceId);
                    device.setDevFaceGbcode(device.getDevNo());
                } else {
                    // 没有则末位补上
                    device.setDevFaceGbcode(device.getDevNo());
                    device.setDevFaceId(faceId + "," + device.getDevNo());
                    device.setDevFaceEngine(engine + ",ali");
                }
            }
        }
        return device;
    }
}
